package cqut.wys.common;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 数据源配置(使用HikariCP数据库连接池数据源)
 * --------神兽出没--------/
 *   ┌─┐     ┌─┐
 * ┌─┘─┴─────┘─┴─┐
 * │      ─      │
 * │  ┬─┘   └─┬  │
 * │             │
 * │      ┴      │  Code is far away from bug with the animal protecting
 * └───┐      ┌──┘  神兽保佑,代码无bug
 *     │      │
 *     │      └──────┐
 *     │             ├┐
 *     │             ┌┘
 *     └┐ ┐ ┌───┬─┐ ┌┘
 *      │ ┤ ┤   │ ┤ ┤
 *      └─┴─┘   └─┴─┘
 * --------感觉萌萌哒--------/
 *
 * @author wuyoushan
 * @date 2018/2/28
 */
@Configuration
public class DatasourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public ConnectionSettings userConnectionSettings(){
        return new ConnectionSettings();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.news")
    public ConnectionSettings newsConnectionSettings(){
        return new ConnectionSettings();
    }

    @Primary //表示优先选择
    @Bean(name = "userDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public DataSource userDatasource(){
        return getHikariDataSource(userConnectionSettings());
    }

    @Bean(name = "newsDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.news")
    public DataSource newsDatasource(){
        return getHikariDataSource(newsConnectionSettings());
    }

    private HikariDataSource getHikariDataSource(ConnectionSettings connectionSettings){
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setUsername(connectionSettings.getUsername());
        hikariDataSource.setPassword(connectionSettings.getPassword());
        hikariDataSource.setJdbcUrl(connectionSettings.getUrl());
        hikariDataSource.setDriverClassName(connectionSettings.getDriverClassName());
        return hikariDataSource;
    }
}
